<template>
  <div class="adv-filter">
    <component
      v-for="item in data"
      :filterData="item"
      :key="item.name"
      :is="switchCom(item)"
      @onChange="onChange"
    ></component>
    <div>
      <div v-for="(item, index) in result" :key="index" @click="remove(item)">
        {{ item.name }} {{ item.label }}
      </div>
    </div>
  </div>
</template>
<script>
import advFilterBase from './filterBase';
import advFilterText from './filterText';
import advFilterTime from './filterTime';
export default {
  props: {
    data: {
      type: Object,
      default: () => {
        return {};
      }
    }
  },
  data() {
    return {
      result: []
    };
  },
  watch: {
    data: {
      handler() {
        this.IntegrationResult();
      },
      deep: true
    }
  },
  // 拷贝一份原始数据
  computed: {
    copyData() {
      return JSON.parse(JSON.stringify(this.data));
    }
  },
  component: {
    advFilterBase,
    advFilterText,
    advFilterTime
  },
  mounted() {
    console.log(this.data);
  },
  methods: {
    switchCom(item) {
      console.log(item);
      let component = null;
      switch (item.type) {
        case 'select':
          component = advFilterBase;
          break;
        case 'date':
          component = advFilterText;
          break;
        case 'text':
          component = advFilterTime;
          break;
      }
      return component;
    },
    // 筛选后的返回值
    onChange(res) {
      for (const key in this.copyData) {
        if (res.id === this.copyData[key].id) {
          console.log(this.copyData[key]);
          this.copyData[key]['value'] = res.value;
        }
      }
      this.IntegrationResult();
    },
    // 整合筛选结果
    /**
     * 将筛选后的数据进行遍历
     * 通过value属性和data属性进行对比看选了那些
     * 就把这些给选出来作为筛选结果
     */
    IntegrationResult() {
      this.result = [];
      for (const key in this.copyData) {
        this.copyData[key].value.map(item => {
          this.copyData[key].data.map(item2 => {
            if (item === item2.value) {
              this.result.push({
                label: item2.label,
                value: item2.value,
                name: this.copyData[key].name,
                id: this.copyData[key].id
              });
            }
          });
        });
      }

      console.log(this.result);
    },
    // 点击删除
    remove(item) {
      let index = this.result.findIndex(val => val.id === item.id && val.value === item.value);
      if (index !== -1) {
        this.result.splice(index, 1);
      }
      for (const key in this.data) {
        if (this.data[key]['id'] === item.id) {
          let i = this.data[key]['value'].findIndex(val => val === item.value);
          this.data[key]['value'].splice(i, 1);
        }
      }
    }
  }
};
</script>
<style scoped></style>
